package com.cn.steam.iam.controller.open;

import com.cn.steam.foundation.common.model.exception.BadRequestException;
import com.cn.steam.foundation.common.web.config.jwt.ServiceContextHolder;
import com.cn.steam.iam.model.po.IamUserRole;
import com.cn.steam.iam.service.IamPartnerProfileService;
import com.cn.steam.iam.service.IamUserRoleProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.cn.steam.foundation.common.model.CommonConstant.OPEN_USER_ROLE_V1_API;

/**
 * @author zjm
 * @date 2021/05/10
 */
@RestController
@RequestMapping(OPEN_USER_ROLE_V1_API)
public class IamUserRoleController {

    @Autowired
    private IamPartnerProfileService iamPartnerProfileService;

    @Autowired
    private IamUserRoleProfileService iamUserRoleProfileService;

    @PreAuthorize("hasAuthority('USER_ROLE_ADD')")
    @PostMapping("/add")
    public List<IamUserRole> add(@Valid @RequestBody List<String> roleIds){
        Set<String> roleIdSet = new HashSet<>(roleIds);
        if(!ServiceContextHolder.getOrInitServiceContext().isAdmin()){
            List<String> partnerRoleList = iamPartnerProfileService.qryPartRoleByPartnerId(ServiceContextHolder.getOrInitServiceContext().getSourceId());
            for(String roleId : roleIdSet){
                if(!partnerRoleList.contains(roleId)){
                    throw new BadRequestException("the user has no role: "+roleId);
                }
            }
        }

        List<IamUserRole> iamUserRoleList = new ArrayList<>();
        for(String roleId : roleIdSet){
            IamUserRole iamUserRole = new IamUserRole();
            iamUserRole.setRoleId(roleId);
            iamUserRole.setUserId(ServiceContextHolder.getOrInitServiceContext().getUserId());
            iamUserRoleList.add(iamUserRole);
        }

        iamUserRoleProfileService.addUserRoleBatch(iamUserRoleList);

        return iamUserRoleList;
    }

}
